import time
from tqsdk import TqApi, TqAuth, TqKq
from rich.console import Console
from rich.theme import Theme

# 定义颜色主题
custom_theme = Theme({
    "info": "bright_cyan",
    "warning": "bright_yellow",
    "error": "bright_red",
    "success": "bright_green",
    "trade": "bold bright_magenta"
})
console = Console(theme=custom_theme)

if __name__ == "__main__":
    try:
        # 使用当前代码的 API 账号和密码
        api = TqApi(account=TqKq(), auth=TqAuth("cps168", "alibaba"))

        while True:
            # 等待数据更新
            #api.wait_update()
            console.print(f"**********{time.strftime('%X')} 未成交订单查询**********", style="warning")

            # 获取所有订单
            orders = api.get_order()
            for order_id, order in orders.items():
                # 检查订单对象是否有 status 属性，并且状态为 ALIVE
                if hasattr(order, 'status') and order.status == "ALIVE":
                    # 提取订单相关信息
                    symbol = getattr(order, 'instrument_id', '未知合约')
                    direction = getattr(order, 'direction', '未知方向')
                    offset = getattr(order, 'offset', '未知开平')
                    limit_price = getattr(order, 'limit_price', '未知价格')
                    volume_orign = getattr(order, 'volume_orign', '未知数量')
                    volume_left = getattr(order, 'volume_left', '未知剩余数量')
                    last_msg = getattr(order, 'last_msg', '无最新消息')

                    # 打印未成交订单信息
                    console.print(
                        f"订单 ID: {order_id}\n"
                        f"合约: {symbol}\n"
                        f"方向: {direction}\n"
                        f"开平: {offset}\n"
                        f"委托价格: {limit_price}\n"
                        f"委托数量: {volume_orign}\n"
                        f"剩余数量: {volume_left}\n"
                        f"最新消息: {last_msg}\n",
                        style="info"
                    )

    except KeyboardInterrupt:
        console.print("用户手动终止程序", style="warning")
    finally:
        # 关闭 API 连接
        api.close()
        console.print("程序已停止", style="info")